//
//  BPAddressViewController.m
//  BabyPhotograph
//
//  Created by cesh on 2017/2/17.
//  Copyright © 2017年 cesh. All rights reserved.
//

#import "BPAddressViewController.h"
#import "BPAddressTableViewCell.h"
#import "BPAddAddressViewController.h"
#import "UILabel+BPBoundingRect.h"
@interface BPAddressViewController ()<UITableViewDelegate, UITableViewDataSource, BPAddressTableViewCellProtocol, AddAddressProtocol>

@property (strong, nonatomic) UITableView *addressTableView;
@property (assign, nonatomic) NSInteger addressCount;
@property (strong, nonatomic) NSArray *data;

//记录下每个cell的高度
@property (strong, nonatomic) NSMutableArray *cellHeights;
//table view整体的高度
@property (assign, nonatomic) CGFloat tableViewHeight;

@end

@implementation BPAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"常用地址";
    
    [self getAddresses];
    
}

- (NSMutableArray *)cellHeights {
    if (_cellHeights == nil) {
        _cellHeights = [NSMutableArray array];
    }
    return _cellHeights;
}

- (void)calculateCellHeights {
    CGFloat tableViewHeight = 0;
    for (NSDictionary *commentData in self.data) {
        [self.cellHeights addObject:@([self heightForCommentData:commentData])];
        tableViewHeight += [self heightForCommentData:commentData];
    }
    self.tableViewHeight = (tableViewHeight > screenH - 64 - 50.5) ? screenH - 64 - 50.5 : tableViewHeight;
}

//根据label的长度和是否有图片计算出cell的高度
- (CGFloat)heightForCommentData:(NSDictionary *)commentData {
    //获取地址文字
    NSString *localString = commentData[@"local"];
    //是否是默认值地址
    BOOL is_default = [commentData[@"is_default"] isEqualToString:@"1"] ? YES : NO;
    if (is_default) {
        localString = [NSString stringWithFormat:@"[默认]%@", localString];
    }
    //拼接上地址详情
    NSString *local_extString = commentData[@"local_ext"];
    localString = [NSString stringWithFormat:@"%@%@",localString, local_extString];
    
    //取得文字Lbl的高度
    UILabel *comment =[[UILabel alloc]initWithFrame:CGRectMake(10, 10, screenW - 20, 0)];
    comment.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    comment.textColor = [UIColor colorWithRed:141/255.0 green:165/255.0 blue:184/255.0 alpha:1/1.0];
    
    comment.text = localString;
    
    comment.numberOfLines = 0; //PS：这句很主要，否则默认行数为1，只显示一行文字后面截断了就没有了
    CGRect myRect = [comment boundingRectWithInitSize:comment.frame.size];
    
    CGFloat lblHeight = myRect.size.height;
    
    return lblHeight + 60;
}

- (void)getAddresses {
    if (self.addressTableView) {
        [self.addressTableView removeFromSuperview];
    }
    [SVProgressHUD showInfoWithStatus:@"读取中..."];
    NSDictionary *user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //接收类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         @"text/plain",
                                                         nil];
    NSDictionary * dict = @{
                            @"token" : user[@"token"]
                            };
    [manager POST:[NSString stringWithFormat:@"%@?c=User&&a=addressList",requestURL]
       parameters:dict
         progress:^(NSProgress * _Nonnull uploadProgress) {
             
         }
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                  NSLog(@"地址列表%@", responseObject[@"data"]);
                  [SVProgressHUD dismiss];
                  NSArray *addresses = responseObject[@"data"];
                  self.data = responseObject[@"data"];
                  self.addressCount = addresses.count;
                  [self calculateCellHeights];
                  UITableView *addressTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenW, self.tableViewHeight)];
                  self.addressTableView = addressTableView;
                  [self.view addSubview:addressTableView];
                  addressTableView.delegate = self;
                  addressTableView.dataSource = self;
                  [addressTableView registerNib:[UINib nibWithNibName:@"BPAddressTableViewCell" bundle:nil] forCellReuseIdentifier:@"addressCell"];
              }
              else {
                  [SVProgressHUD showInfoWithStatus:@"请求失败"];
                  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                      [SVProgressHUD dismiss];
                  });
              }
          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              [SVProgressHUD showInfoWithStatus:@"网络故障"];
              dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                  [SVProgressHUD dismiss];
              });
          }];
}

#pragma mark - add address table view cell protocol
- (void)pushEditAddressController:(NSInteger)index {
    BPAddAddressViewController *editAddressVC = [[BPAddAddressViewController alloc]init];
    editAddressVC.title = @"编辑地址";
    editAddressVC.delegate = self;
    //获取旧地址的id
    NSString *oldID = self.data[index][@"id"];
    editAddressVC.old_id = oldID;
    [self.navigationController pushViewController:editAddressVC animated:YES];
}

- (void)deleteAddressCell:(NSInteger)index {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"删除地址" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //删除地址
        NSDictionary *user = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
        //获取要删除的address_id
        NSString *address_id = self.data[index][@"id"];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //接收类型不一致请替换一致text/html或别的
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             @"text/plain",
                                                             nil];
        NSDictionary * dict = @{
                                @"token" : user[@"token"],
                                @"address_id" : address_id
                                };
        [manager POST:[NSString stringWithFormat:@"%@?c=User&&a=deleteAddress",requestURL]
           parameters:dict
         progress:^(NSProgress * _Nonnull uploadProgress) {
             
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
                 NSLog(@"删除地址成功");
                 [self getAddresses];
             }
             else {
                 NSLog(@"%@", responseObject[@"data"]);
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             
         }];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:confirm];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

#pragma mark - table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.cellHeights[indexPath.row] floatValue];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BPAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addressCell"];
    //首先判断是否是默认地址
    BOOL is_default = [self.data[indexPath.row][@"is_default"] isEqualToString:@"1"] ? YES : NO;
    
    UILabel *defaultLabel = [[UILabel alloc] init];
    defaultLabel.origin = CGPointMake(10, 10);
    defaultLabel.text = @"[默认]";
    defaultLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    defaultLabel.textColor = [UIColor colorWithRed:118/255.0 green:177/255.0 blue:253/255.0 alpha:1/1.0];
    [defaultLabel sizeToFit];
    
    UILabel *location = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, screenW - 20, 0)];
    location.textColor = [UIColor colorWithRed:0x8d/255.0 green:0xa5/255.0 blue:0xb8/255.0 alpha:1/1.0];
    location.text = self.data[indexPath.row][@"local"];
    location.origin = CGPointMake(10, 10);
    //判断如果是默认地址
    if (is_default) {
        [cell.contentView addSubview:defaultLabel];
        location.text = [NSString stringWithFormat:@"           %@", location.text];
    }
    location.text = [NSString stringWithFormat:@"%@%@", location.text, self.data[indexPath.row][@"local_ext"]];
    
    location.numberOfLines = 0; //PS：这句很主要，否则默认行数为1，只显示一行文字后面截断了就没有了
    CGRect myRect = [location boundingRectWithInitSize:location.frame.size];
    location.frame = CGRectMake(10, 10, screenW - 20, myRect.size.height);
    
    [cell.contentView addSubview:location];
    
    cell.index = indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    return cell;
}
//用于下订单时候的地址选择
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *selectedAddress = self.data[indexPath.row];
    if ([self.delegate respondsToSelector:@selector(selectedAddress:)]) {
        [self.delegate selectedAddress:selectedAddress];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction)addNewAddress:(UIButton *)sender {
    BPAddAddressViewController *addAddressVC = [[BPAddAddressViewController alloc]init];
    addAddressVC.title = @"添加新地址";
    addAddressVC.delegate = self;
    [self.navigationController pushViewController:addAddressVC animated:YES];
}

- (void)reloadAddress {
    [self getAddresses];
}

@end
